import axios from 'axios';
import {Base64} from 'js-base64'
import {JsHelper} from "@/utils/js-helper.js"

///////// axios实例 /////////
const native = axios.create({
    //baseURL: process.env.VUE_APP_BASE_API, // api的base_url
    timeout: 3000 // 请求超时时间
});

const http = axios.create({
    //baseURL: process.env.VUE_APP_BASE_API, // api的base_url
    timeout: 3000 // 请求超时时间
});

// 请求拦截器
http.interceptors.request.use(
    async config => {
        console.log('axios request:', config);
        let original = config.url;
        let parser = parseURL(original);
        let url = parser.protocol + '://' +parser.host + ':'+parser.port;
        let auth = {name:'root',password:'123456'}
        let token = "Basic "+Base64.encode(auth.name+':'+auth.password);
        // 判定是否开启权限校验, 如果开启, 则补全 authorization 请求头信息
        let etcdAuthEnabled = false;
        await native.get(url+'/v2/auth/enable')
            .then(res=>{
                etcdAuthEnabled = res.data.enabled;
            })
            .catch(error=>{
                etcdAuthEnabled = false;
                throw error;
            });
        if(etcdAuthEnabled){
            config.headers.Authorization = token;
        }
        return config;
    },
    error => {
        // 请求错误处理
        return Promise.reject(error);
    }
);

// 响应拦截器
http.interceptors.response.use(
    response => {
        // 对响应数据做处理，例如只返回data部分
        console.log("axios response:",response)
        const code = response.status;
        // 如果返回的状态码为200，说明成功，可以直接返回数据
        if (isHttpSuccessful(code)) {
            return response;
        } else {
            // 其他状态码都当作错误处理
            return Promise.reject(response || 'error');
        }
    },
    error => {
        // 服务器状态码不为200时的错误处理
        return Promise.reject(error);
    }
);

function isHttpSuccessful(status) {
    return status >= 200 && status < 300;
}

function parseURL(url) {
    const regex = /^(https?):\/\/([^:/?]+)(?::(\d+))?([^?#]+)?(\?[^#]+)?(#.+)?$/;
    const match = url.match(regex);
    if (!match) return null;
    const [, protocol, host, port, path, query, fragment] = match;
    const parsedURL = {
        protocol: protocol,
        host: host,
        port: port ? parseInt(port) : null,
        path: path || null,
        query: query ? query.slice(1) : null,
        fragment: fragment ? fragment.slice(1) : null
    };
    return parsedURL;
}

/**
 * 使用原始请求,不添加拦截器
 * @param hostport
 * @returns {Promise<axios.AxiosResponse<any>>}
 */
export function native_cluster_version(hostport) {
    return native.get(hostport+'/version');
}

// etcd 接口方法
export function cluster_health(hostport) {
    return http.get(hostport+'/health');
}

export function cluster_version(hostport) {
    return http.get(hostport+'/version');
}

export function etcd_keys_list(hostport) {
    return http.get(hostport+'/v2/keys?recursive=true');
}

export function etcd_keys_get(hostport,key) {
    if(JsHelper.string.startsWith(key,"/")){
        key = JsHelper.string.replaceFirst(key,"/","");
    }
    return http.get(hostport+'/v2/keys/'+key);
}

/**
 * Creating an in-order key
 * @param hostport
 * @param key
 * @param form
 * @returns {Promise<axios.AxiosResponse<any>>}
 */
export function etcd_keys_post(hostport, key, form) {
    if(JsHelper.string.startsWith(key,"/")){
        key = JsHelper.string.replaceFirst(key,"/","");
    }
    return http.post(hostport+'/v2/keys/'+key,{},{params:form});
}

export function etcd_keys_put(hostport, key, form) {
    if(JsHelper.string.startsWith(key,"/")){
        key = JsHelper.string.replaceFirst(key,"/","");
    }
    return http.put(hostport+'/v2/keys/'+key,{},{params:form});
}

export function etcd_keys_delete(hostport, key, form) {
    if(JsHelper.string.startsWith(key,"/")){
        key = JsHelper.string.replaceFirst(key,"/","");
    }
    return http.delete(hostport+'/v2/keys/'+key,{},{
        headers:{"Content-Type": "application/x-www-form-urlencoded"},
        params:form
    });
}

export function etcd_dir_delete(hostport, key) {
    if(JsHelper.string.startsWith(key,"/")){
        key = JsHelper.string.replaceFirst(key,"/","");
    }
    return http.delete(hostport+'/v2/keys/'+key+'?dir=true&recursive=true');
}

export function auth_user_get(hostport) {
    return http.get(hostport+'/v2/auth/users');
}

export function auth_user_add(hostport, user, data) {
    return http.put(hostport+'/v2/auth/users/'+user,data);
}

export function auth_user_delete(hostport,user) {
    return http.delete(hostport+'/v2/auth/users/'+user);
}

export function auth_user_grant(hostport,user,data) {
    return http.put(hostport+'/v2/auth/users/'+user,data);
}

export function auth_user_revoke(hostport,user,data) {
    return http.put(hostport+'/v2/auth/users/'+user,data);
}

export function auth_role_list(hostport) {
    return http.get(hostport+'/v2/auth/roles');
}

export function auth_role_get(hostport,name) {
    return http.get(hostport+'/v2/auth/roles/'+name);
}

export function auth_role_add(hostport,name) {
    return http.put(hostport+'/v2/auth/roles/'+name,{"role":name});
}

export function auth_role_delete(hostport,name) {
    return http.delete(hostport+'/v2/auth/roles/'+name,{"role":name});
}

export function auth_role_grant(hostport,name,data) {
    return http.put(hostport+'/v2/auth/roles/'+name,data);
}

export function auth_role_revoke(hostport,name,data) {
    return http.put(hostport+'/v2/auth/roles/'+name,data);
}

export function is_auth_enabled(hostport){
    return http.get(hostport+'/v2/auth/enable');
}

export function auth_enable(hostport) {
    return http.put(hostport+'/v2/auth/enable', {});
}

export function auth_disable(hostport) {
    return http.delete(hostport+'/v2/auth/enable');
}

export function cluster_members(hostport) {
    return http.get(hostport+'/v2/members');
}

export function stats_leader(hostport) {
    return http.get(hostport+'/v2/stats/leader');
}

/**
 * 使用原始请求, 不添加拦截器
 * @param hostport
 * @returns {Promise<axios.AxiosResponse<any>>}
 */
export function native_stats_self(hostport) {
    return native.get(hostport+'/v2/stats/self');
}

export function stats_self(hostport) {
    return http.get(hostport+'/v2/stats/self');
}

export function stats_store(hostport) {
    return http.get(hostport+'/v2/stats/store');
}



